package com.lanou.moving.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lanou.moving.R;
import com.lanou.moving.activity.PlayMusicActivity;
import com.lanou.moving.activity.SongListDetailActivity;
import com.lanou.moving.adapter.AlbumDetailAdapter;
import com.lanou.moving.base.BaseFragment;
import com.lanou.moving.constant.URL;
import com.lanou.moving.entity.AlbumDetailRoot;
import com.lanou.moving.entity.MusicInfo;
import com.lanou.moving.entity.dao.AddTo;
import com.lanou.moving.entity.dao.AddToDao;
import com.lanou.moving.entity.dao.Collection;
import com.lanou.moving.entity.dao.CollectionDao;
import com.lanou.moving.service.DownloadServices;
import com.lanou.moving.entity.dao.RecentlyPlay;
import com.lanou.moving.entity.dao.RecentlyPlayDao;
import com.lanou.moving.eventBus.MyEventBus;
import com.lanou.moving.singleton.DaoSingleton;
import com.lanou.moving.view.CDSPopupWindow;
import com.lanou.moving.view.MyListView;
import com.lanou.moving.volley.StringRequestUtf;
import com.lanou.moving.volley.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import it.sephiroth.android.library.picasso.Picasso;



/**
 * Created by 梁树珍 on 15/11/2.
 */
public class AlbumDetailFragment extends BaseFragment implements AlbumDetailAdapter.OnMenuClickListener,
        View.OnClickListener, AdapterView.OnItemClickListener {
    private MyListView album_detail_listView;
    private AlbumDetailAdapter adapter;
    private AlbumDetailRoot.DataEntity dataEntities;
    private List<AlbumDetailRoot.DataEntity.SongListEntity> songListEntities;
    private List<MusicInfo> musicInfoList;
    private StringRequestUtf request;
    private VolleySingleton volleySingleton;
    private long albumId;
    private ImageView album_detail_bg;
    private Toolbar coordinator_toolbar;
    private CollapsingToolbarLayout collapsing_toolbar;
    private TextView songs_list_collection;// 收藏歌单
    //数据库表
    private CollectionDao collectionDao;
    private AddToDao addToDao;
    private RecentlyPlayDao recentlyPlayDao;
    private View views;
    private TextView collect_tv;
    private ImageView rankingListBackground;
    private List<Collection> collections;
    private CDSPopupWindow pw;
    private View view;
    private int index = 1000;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_ranking_list_detail, null);
        volleySingleton = VolleySingleton.getInstance(mContext);

        album_detail_listView = (MyListView) view.findViewById(R.id.songs_list_listview);
        album_detail_listView.setOnItemClickListener(this);

        album_detail_bg = (ImageView) view.findViewById(R.id.songs_list_bg);
        collapsing_toolbar = (CollapsingToolbarLayout) view.findViewById(R.id.collapsing_toolbar);

        rankingListBackground = (ImageView) view.findViewById(R.id.new_song_background);
        songs_list_collection = (TextView) view.findViewById(R.id.songs_list_collection);
        songs_list_collection.setOnClickListener(this);

        coordinator_toolbar = (Toolbar) view.findViewById(R.id.coordinator_toolbar);
        coordinator_toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getFragmentManager().popBackStack();
            }
        });
        albumId = getArguments().getLong("albumId");
        getData();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        collectionDao = DaoSingleton.getInstance().getCollectionDao();
        addToDao = DaoSingleton.getInstance().getAddToDao();
        recentlyPlayDao = DaoSingleton.getInstance().getRecentlyPlayDao();
        views = LayoutInflater.from(mContext).inflate(R.layout.layout_song, null);
        collect_tv = (TextView) views.findViewById(R.id.layout_song_collection);
    }

    public void getData() {
        String url = URL.ALBUM_DETAIL_START + albumId + URL.ALBUM_DETAIL_END;
        request = new StringRequestUtf(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                AlbumDetailRoot albums = gson.fromJson(response, AlbumDetailRoot.class);
                dataEntities = albums.getData();
                songListEntities = dataEntities.getSongList();
                adapter = new AlbumDetailAdapter(mContext, songListEntities);
                adapter.setOnMenuClickListener(AlbumDetailFragment.this);
                album_detail_listView.setAdapter(adapter);
                Picasso.with(mContext).load(dataEntities.getPicUrl()).into(album_detail_bg);
                collapsing_toolbar.setTitle(dataEntities.getName());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(request);
    }

    @Override
    public void onMenuClick(final AlbumDetailRoot.DataEntity.SongListEntity songsEntity) {
        rankingListBackground.setVisibility(View.VISIBLE);
        collections = collectionDao.queryBuilder().where(
                CollectionDao.Properties.SongId.eq(songsEntity.getSongId())).list();
        if (collections != null && collections.size() > 0) {
            collect_tv.setText("取消收藏");
        }else{
            collect_tv.setText("收藏");
        }
        pw = new CDSPopupWindow(mContext, views, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.layout_song_collection:
                        if ("收藏".equals(collect_tv.getText())) {
                            Collection collection = new Collection();
                            collection.setSongId(songsEntity.getSongId());
                            collection.setSongName(songsEntity.getName());
                            collection.setPlayUrl(songsEntity.getUrlList().get(0).getUrl());
                            collection.setAlbumId(songsEntity.getAlbumId());
                            collection.setDuration((long) songsEntity.getUrlList().get(0).getDuration());
                            collection.setSingerName(songsEntity.getSingerName());
                            collectionDao.insert(collection);
                            collect_tv.setText("取消收藏");
                            Toast.makeText(mContext, "已收藏", Toast.LENGTH_LONG).show();
                            pw.dismiss();
                        } else if ("取消收藏".equals(collect_tv.getText())) {
                            collectionDao.queryBuilder().where(CollectionDao.Properties.SongId
                                    .eq(songsEntity.getSongId())).buildDelete()
                                    .executeDeleteWithoutDetachingEntities();
                            collect_tv.setText("收藏");
                            Toast.makeText(mContext, "已取消收藏", Toast.LENGTH_LONG).show();
                            pw.dismiss();
                        }
                        break;
                    case R.id.layout_song_download:
                        if (songsEntity.getAuditionList() == null ||
                                songsEntity.getAuditionList().size() == 0 ||
                                songsEntity.getAuditionList().size() == 1) {
                            Toast.makeText(getActivity(), "暂无资源", Toast.LENGTH_LONG).show();

                        } else if (songsEntity.getAuditionList().size() > 1) {
                            String download_url = songsEntity.getAuditionList().get(1).getUrl();
                            startDownloadService(index, download_url, songsEntity.getName(), songsEntity.getSingerName());
                            index++;
                            pw.dismiss();
                        }
                            break;
                            case R.id.layout_song_share:
                                break;
                        }

                }
        }, rankingListBackground);
        pw.showAtLocation(view.findViewById(R.id.coordinator_layout), Gravity.CENTER, 0, 0);
    }
    private void startDownloadService(int notifyId, String url, String songName, String singerName) {     //绑定服务类
        Intent intent = new Intent(getActivity(), DownloadServices.class);
        intent.putExtra("url", url);
        intent.putExtra("singerName", singerName);
        intent.putExtra("songName", songName);
        intent.putExtra("notifyId", notifyId);
        getActivity().startService(intent);
    }

    @Override
    public void onResume() {
        super.onResume();
        List<AddTo> lists = addToDao.queryBuilder().where(AddToDao.Properties.SongListId.eq(albumId)).list();
        if (lists != null && lists.size() > 0) {
            songs_list_collection.setText("取消收藏");
        } else {
            songs_list_collection.setText("收藏");
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.songs_list_collection:
                if ("收藏".equals(songs_list_collection.getText())) {
                    AddTo addTo = new AddTo();
                    addTo.setName(dataEntities.getName());
                    addTo.setSongListId((int) albumId);
                    addTo.setPicUrl(dataEntities.getPicUrl());
                    addTo.setSongs(songListEntities.size());
                    addTo.setResource("发现");
                    addToDao.insert(addTo);
                    songs_list_collection.setText("取消收藏");
                    Toast.makeText(mContext, "已加入收藏", Toast.LENGTH_LONG).show();
                } else if ("取消收藏".equals(songs_list_collection.getText())) {
                    addToDao.queryBuilder().where(AddToDao.Properties.SongListId.eq(albumId)).buildDelete()
                            .executeDeleteWithoutDetachingEntities();
                    songs_list_collection.setText("收藏");
                    Toast.makeText(mContext, "已取消收藏", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        AlbumDetailRoot.DataEntity.SongListEntity songsEntity =
                (AlbumDetailRoot.DataEntity.SongListEntity) parent.getItemAtPosition(position);
        if ((songsEntity.getUrlList() != null && songsEntity.getUrlList().size() > 0)) {
            RecentlyPlay recentlyPlay = new RecentlyPlay();
            recentlyPlay.setSongName(songsEntity.getName());
            recentlyPlay.setPlayUrl(songsEntity.getUrlList().get(0).getUrl());
            recentlyPlay.setDuration((long) songsEntity.getUrlList().get(0).getDuration());
            recentlyPlay.setSingerName(songsEntity.getSingerName());
            recentlyPlay.setSongId((long) songsEntity.getSongId());
            recentlyPlay.setResource("网络");
            recentlyPlayDao.insertOrReplace(recentlyPlay);

            EventBus.getDefault().post(new MyEventBus.PlayMusic(1));
            musicInfoList = new ArrayList<>();

            for (AlbumDetailRoot.DataEntity.SongListEntity entity : songListEntities) {
                if (entity.getUrlList() != null && entity.getUrlList().size() > 0) {
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setSongName(entity.getName());
                    musicInfo.setAlbum(entity.getAlbumName());
                    musicInfo.setAlbumId(entity.getAlbumId());
                    musicInfo.setUrl(entity.getUrlList().get(0).getUrl());
                    musicInfo.setDuration(entity.getUrlList().get(0).getDuration());
                    musicInfo.setSingerName(entity.getSingerName());
                    musicInfo.setResouce("网络");
                    musicInfoList.add(musicInfo);
                }
            }

            Intent intent = new Intent(mContext, PlayMusicActivity.class);
            EventBus.getDefault().post(new MyEventBus.Deliver(musicInfoList, songsEntity.getName()));
            intent.putExtra("songName", songsEntity.getName());
            intent.putExtra("duration", songsEntity.getUrlList().get(0).getDuration());
            intent.putExtra("resource", "网络");
            intent.putExtra("albumId", songsEntity.getAlbumId());
            intent.putExtra("singerName", songsEntity.getSingerName());
            startActivity(intent);
        } else {
            Toast.makeText(mContext, "暂时无法播放此歌曲", Toast.LENGTH_LONG).show();
        }
    }
}
